# 1.使用sklearn中iris数据，完成以下操作
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# 读取数据
import numpy as np
data = load_iris()
x = data.data
y = data.target
y = y.reshape(-1, 1)
print(x.shape)
print(y.shape)

# 将数据切分为训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=123)

# 将数据放入管道，使用map对特征进行归一化处理，批处理32条数据，多余数据丢弃
import tensorflow as tf
from tensorflow.keras import layers, models, metrics, optimizers, losses
import numpy as np

def fn(x, y):
    x = (x - tf.reduce_min(x, axis=0))/ (tf.reduce_max(x, axis=0) - tf.reduce_min(x, axis=0))
    y = tf.cast(y, tf.int32)
    return x, y

ds_train = tf.data.Dataset.from_tensor_slices((x_train, y_train))
ds_train = ds_train.map(fn).batch(32, drop_remainder=True).shuffle(500)

ds_test = tf.data.Dataset.from_tensor_slices((x_test, y_test))
ds_test = ds_test.map(fn).batch(32, drop_remainder=True).shuffle(300)

# 创建模型
# 添加两个隐藏层，神经元数量分别为8,4，使用relu进行激活，dropout正则，系数为0.4
model = models.Sequential([
    layers.Dense(8),
    layers.Activation('relu'),
    layers.Dropout(0.1),
    layers.Dense(4),
    layers.Activation('relu'),
    layers.Dropout(0.1),
    layers.Dense(3, activation='softmax')
])
model.build(input_shape=[None, 4])
model.compile(optimizers.Adam(0.01),
              loss=losses.SparseCategoricalCrossentropy(),
              metrics=['accuracy'])
# 训练过程中添加验证集，验证集为训练集10%数据
model.fit(ds_train, epochs=1000)
# 使用matplotlib绘制训练及验证集loss和acc曲线
# 使用tensorboard进行可视化处理
# 打印测试集损失和准确率